package com.ychs.lawyerback01.controller;


import com.ychs.lawyerback01.annotation.RequirePermission;
import com.ychs.lawyerback01.common.R;
import com.ychs.lawyerback01.common.ResultCode;
import com.ychs.lawyerback01.pojo.UploadEntity;
import com.ychs.lawyerback01.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/documents")
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    /**
     * 上传文档
     */
    @PostMapping("/upload")
    public R<UploadEntity> uploadDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("seekerName") String seekerName) {
        try {
            UploadEntity uploadEntity = documentService.uploadDocument(file, seekerName);
            return R.success(uploadEntity);
        } catch (IOException e) {
            return R.fail(ResultCode.FILE_UPLOAD_ERROR);
        } catch (IllegalArgumentException e) {
            return R.fail(ResultCode.PARAMS_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 获取文档列表（支持搜索条件）
     */
    @RequirePermission("system:admin:pending")
    @GetMapping("/pending")
    public R<List<UploadEntity>> getPendingDocuments(
            @RequestParam(required = false) String fileName,
            @RequestParam(required = false) String seekerName,
            @RequestParam(required = false) String status) {
        try {
            List<UploadEntity> documents = documentService.getPendingDocuments(fileName, seekerName, status);
            return R.success(documents);
        } catch (Exception e) {
            return R.fail(ResultCode.ERROR);
        }
    }

    /**
     * 分页查询文档
     */
   @RequirePermission("system:admin:list")
    @GetMapping("/list")
    public R<Map<String, Object>> getDocumentsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String fileName,
            @RequestParam(required = false) String seekerName,
            @RequestParam(required = false) String status) {
        try {
            System.out.println("接收参数: page=" + page + ", pageSize=" + pageSize +
                    ", fileName=" + fileName + ", seekerName=" + seekerName +
                    ", status=" + status);

            Map<String, Object> result = documentService.getDocumentsByPage(page, pageSize, fileName, seekerName, status);

            System.out.println("查询结果: " + result);
            return R.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.ERROR.getCode(), "系统异常: " + e.getMessage());
        }
    }

    /**
     * 审核通过文档
     */
    @RequirePermission("system:admin:approve")
    @PostMapping("/{id}/approve")
    public R<UploadEntity> approveDocument(
            @PathVariable Long id,
            @RequestParam String approvedBy) {
        try {
            UploadEntity uploadEntity = documentService.approveDocument(id, approvedBy);
            return R.success(uploadEntity);
        } catch (RuntimeException e) {
            return R.fail(ResultCode.DOCUMENT_NOT_FOUND.getCode(), e.getMessage());
        }
    }

    /**
     * 驳回文档
     */
    @RequirePermission("system:admin:reject")
    @PutMapping("/{id}/reject")
    public R<UploadEntity> rejectDocument(
            @PathVariable long id,
            @RequestParam String approvedBy,
            @RequestParam String comments) {
        try {
            UploadEntity uploadEntity = documentService.rejectDocument(id, approvedBy, comments);
            return R.success(uploadEntity);
        } catch (RuntimeException e) {
            return R.fail(ResultCode.DOCUMENT_NOT_FOUND.getCode(), e.getMessage());
        }
    }

    /**
     * 根据ID获取文档详情
     */
    @GetMapping("/{id}")
    public R<UploadEntity> getDocumentById(@PathVariable Long id) {
        try {
            UploadEntity uploadEntity = documentService.getDocument(id);
            return R.success(uploadEntity);
        } catch (RuntimeException e) {
            return R.fail(ResultCode.DOCUMENT_NOT_FOUND);
        }
    }

    /**
     * 下载模板文件
     */
    @GetMapping("/template")
    public ResponseEntity<Resource> downloadTemplate() throws IOException {
        Resource resource = new ClassPathResource("templates/DemandTemp.docx");
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"DemandTemp.docx\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
    @GetMapping("/download/{id}")
    @RequirePermission("system:admin:download")
    public ResponseEntity<Resource> downloadDocument(@PathVariable Long id) {
        try {
            UploadEntity uploadEntity = documentService.getDocument(id);
            if (uploadEntity == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            File file = new File(uploadEntity.getFilePath());
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            Resource resource = new FileSystemResource(file);

            String encodedFileName = URLEncoder.encode(uploadEntity.getFileName(), StandardCharsets.UTF_8.name())
                    .replaceAll("\\+", "%20");

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName)
                    .header(HttpHeaders.CONTENT_TYPE, getMimeType(uploadEntity.getFileType()))
                    .contentLength(file.length())
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    private String getMimeType(String fileType) {
        switch (fileType.toLowerCase()) {
            case "pdf": return "application/pdf";
            case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            default: return "application/octet-stream";
        }
    }
    @GetMapping("/preview/{id}")
    @RequirePermission("system:admin:preview")
    public ResponseEntity<Resource> previewDocument(@PathVariable Long id) {
        try {
            UploadEntity uploadEntity = documentService.getDocument(id);
            if (uploadEntity == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            File file = new File(uploadEntity.getFilePath());
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            Resource resource = new FileSystemResource(file);

            MediaType mediaType;
            if ("docx".equalsIgnoreCase(uploadEntity.getFileType())) {
                mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            } else if ("pdf".equalsIgnoreCase(uploadEntity.getFileType())) {
                mediaType = MediaType.APPLICATION_PDF;
            } else {
                mediaType = MediaType.APPLICATION_OCTET_STREAM;
            }

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(uploadEntity.getFileName(), StandardCharsets.UTF_8.name())
                    .replaceAll("\\+", "%20");

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName)
                    .contentType(mediaType)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace(); // 记录异常信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}